<?php
namespace jy_kefu;
defined('BY_JYA') or exit('error');
class kefu extends \plugin{
	public function add($kefuinfo=array()){
		$post=$kefuinfo;
		$data=array(
			'nickname'=>trim($post['nickname']),
			'name'=>trim($post['name']),
			'picurl'=>trim($post['picurl']),
			'groupid'=>intval($post['groupid']),
			'type'=>intval($post['type']),
			'mpname'=>trim($post['mpname']),
			'number'=>trim($post['number']),
			'isadmin'=>intval($post['isadmin']),
			'showkfqr'=>trim($post['showkfqr']),
			'kefuqr'=>trim($post['kefuqr']),
			'paixu'=>intval($post['paixu']),
			'welcometext'=>trim($post['welcometext']),
			'fansauto'=>trim($post['fansauto']),
			'kefuauto'=>trim($post['kefuauto']),
			'autoset'=>intval($post['autoset']),
			'onlinetime'=>ijson_encode($post['onlinetime']),
			'offlinetext'=>trim($post['offlinetext']),
			'isonline'=>intval($post['isonline']),
			'isshow'=>intval($post['isshow']),
			'wxappid'=>intval($post['wxappid']),
			'mid'=>intval($post['mid']),
			'plugin'=>trim($post['plugin']),
			'pid'=>intval($post['merchid']),
		);
		$id=intval($post['id']);
		$keyid=intval($post['keyid']);
		$type=intval($post['type']);
		if($type == 4 || $type == 5){
			$backdata=array(
					'title'=>'全网客服-'.$_SESSION['uniacid'],
					'backtype'=>8,
					'action'=>'wechat',
					'status'=>1,
					'keyword'=>'客服:'.trim($post['name']).'@'.$_SESSION['uniacid'],
					'key'=>$_SESSION['uniacid'].'name'.$post['name'],
			);
			if(empty($keyid)){
				$keyid = cfc('core')->save_back($backdata,'jy_kefu');
				$data['keyid']=$keyid;
			}
			if(empty($qrticket)){
				$title = '全网客服-客服：'.$post['name'].'de二维码';
				$getqrdata=array(
					'keyid'=>$keyid,
				);
				$getqrdata = ijson_encode($getqrdata);
				$qr = cfc('account')->get_qr(2,'jy_kefu',$getqrdata,30,$title);	
				$data['qrticket']=$qr['ticket'];
			}
		}
		if(empty($post['name'])){
			exi('请填写客服账号！','error');
		}
		$kf_account=trim($post['name']).'@'.trim($post['mpname']);
		$nickname=trim($post['nickname']);
		$isadd=pdo_getcolumn('jy_kefus',array('name' => $post['name'],'uniacid'=>$_SESSION['uniacid']),'id');
		$id=$isadd?$isadd:$id;
		if($id){
			if($type == 4 || $type == 5){
				$content = cfc('kefu')->upkefuinfo($kf_account,$nickname);
				if($content['errcode'] == 65401){
					cfc('kefu')->setkefu($kf_account,$nickname);
				}elseif($content['errcode'] != 0){
					exi(cfc('kefu')->error_code($content['errcode']),'error');
				}
			}
			pdo_update('jy_kefus',$data,array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		}else{
			if($type == 4 || $type == 5){
				cfc('kefu')->setkefu($kf_account,$nickname);
			}
			if(pdo_getcolumn('jy_kefus',array('name' => $post['name'],'uniacid'=>$_SESSION['uniacid']),'id')){
				exi('非常抱歉，此账号已被使用，你需要更换客服账号！','error');
			}
			$data['uniacid']=$_SESSION['uniacid'];
			pdo_insert('jy_kefus',$data);
		}
	}
	public function getchatid($mid,$getmid){
		global $_AR;
		if(empty($mid) || empty($getmid)){
			exi('缺少必要参数','error');
		}
		$chats = pdo_getall('jy_kefu_member_chat',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
		$getchats = pdo_getall('jy_kefu_member_chat',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$getmid),array('chatid'),'chatid');
		$getchats=array_keys($getchats);
		foreach($chats as $k=>$v){
			if(in_array($v['chatid'],$getchats)){
					$chatid = $v['chatid'];
			}else{
				unset($chats[$k]);
			}
		}
		if(empty($chatid)){
			pdo_insert('jy_kefu_chat',array('uniacid'=>$_SESSION['uniacid']));
			$chatid = pdo_insertid();
			if($chatid){
				$setdata=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'getmid'=>$getmid,'lasttime'=>TIMESTAMP,'chatid'=>$chatid);
				$getdata=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$getmid,'getmid'=>$mid,'lasttime'=>TIMESTAMP,'chatid'=>$chatid);
				pdo_insert('jy_kefu_member_chat',$setdata);
				pdo_insert('jy_kefu_member_chat',$getdata);
			}
		}
		return $chatid;
	}
	public function getmember($getmid){
		global $_AR;
		if(empty($getmid)){
			exi('缺少必要参数!','error');
		}
		$kefu = pdo_get('jy_kefus',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$getmid),array('id','nickname','name','picurl','isonline'));
		$member=pdo_get('core_members',array('id'=>$getmid,'uniacid'=>$_SESSION['uniacid']),array('avatar','nickname'));
		$getmember = pdo_get('jy_kefu_member',array('uniacid'=>$_SESSION['uniacid'],'id'=>$getmid),array('id','name','logo','realname','phone','iskefu'));
		if(empty($getmember)){
			pdo_insert('jy_kefu_member',array('id'=>$getmid,'uniacid'=>$_SESSION['uniacid'],'name'=>$member['nickname'],'logo'=>$member['avatar']));
			$getmember = pdo_get('jy_kefu_member',array('uniacid'=>$_SESSION['uniacid'],'id'=>$getmid),array('id','name','logo','realname','phone','iskefu'));
		}
		if($kefu){
				$getmember['iskefu'] = 1;
				$getmember['name'] = $kefu['nickname'];
				$getmember['logo'] = $kefu['picurl'];
		}elseif($getmember['name'] !=$member['nickname']){
			$getmember['name'] = $member['nickname'];
		}
		return $getmember;
	}
	public function upmember($setmid,$openid){
		global $_AR;
		if(empty($setmid)){
			exi('缺少必要参数.','error');
		}
		$member=pdo_get('core_members',array('id'=>$getmid,'uniacid'=>$_SESSION['uniacid']),array('avatar','nickname'));
		$kefu = pdo_get('jy_kefus',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$setmid),array('id','name','picurl','isonline'));
		$setmember = pdo_getall('jy_kefu_member',array('uniacid'=>$_SESSION['uniacid'],'id'=>$setmid));
		$nologo=pdo_getcolumn('jy_kefu_set',array('uniacid'=>$_SESSION['uniacid']),'nologo');
		if(empty($setmember)){
			$membernew=array(
					'uniacid' => $_SESSION['uniacid'],
					'id' => $setmid,
			);
			if($kefu){
					$membernew['iskefu'] = 1;
					$membernew['name'] = $kefu['name'];
					$membernew['logo'] = $kefu['picurl'];
					$membernew['openid'] = $kefu['mid'];
			}else{
				if(empty($_SESSION['openid'])){
						$membernew['name'] = $member['nickname'];
						$membernew['logo'] = $member['avatar'];
						$membernew['openid'] = $_SESSION['uid'];
				}else{
						$info = pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'openid'=>$openid));
						$membernew['openid'] = $openid;
						if($info){
								$membernew['logo'] = $info['avatar'];
								$membernew['name'] = $info['nickname'];
						}else{
								$membernew['name'] = '匿名用户';
								$membernew['logo'] = $nologo;
						}		
				}
			}
			pdo_insert('jy_kefu_member',$membernew);
			$member = pdo_get('jy_kefu_member',array('uniacid'=>$_SESSION['uniacid'],'id'=>$_SESSION['uid']));
			return $member;
		}
		
	}
	public function addchatlog($chatmsg,$chatid,$getmid,$type=1,$audiotime=0,$setmid=0){
		$chatmsg = trim($chatmsg);
		if(empty($chatmsg)){
			$return['error'] = 1;
			$return['msg'] = '请输入对话内容！';
			exi($return);
		}
		if(empty($chatid)){
			$return['error'] = 1;
			$return['msg'] = '会话丢失！';
			exi($return);
		}
		$getmid = intval($getmid);
		$setting=pdo_get('jy_kefu_set',array('uniacid'=>$_SESSION['uniacid']),array('title','tpl_kefu','isremind','sharetitle','sharedes','sharepicurl','kefuremindtime','bgcolor','nologo','isautomsg','autotype','isunfollow','filterword','confcolor','groupremind','groupremindtime','groupshowindex','showgroupnum','jyrobotkey','isjyrobot'));
		if(empty($_SESSION['uid'])){
			$return['error'] = 1;
			$return['msg'] = '请先登录会员！';
			exi($return);
		}else{
			$data['setmid'] = $setmid?:$_SESSION['uid'];
			$jqruserid = $data['setmid'];
			$data['nickname'] = empty($_SESSION['member']['nickname']) ? '匿名用户' : $_SESSION['member']['nickname'];
			$data['avatar'] =  empty($_SESSION['member']['avatar']) ? tomedia($setting['nologo']) : $_SESSION['member']['avatar'];
		}
		$data['getmid'] = $getmid;
		$data['createtime'] = TIMESTAMP;
		$data['msg'] = $chatmsg;
		$data['uniacid'] = $_SESSION['uniacid'];
		$data['chatid'] = intval($chatid);
		$type = intval($type);
		$data['type'] = $type;
		$data['audiotime'] = intval($audiotime/1000);
		pdo_insert('jy_kefu_chatlog',$data);
		$logid = pdo_insertid();
		$chat = pdo_get('jy_kefu_member_chat',array('chatid'=>$data['chatid'],'uniacid'=>$_SESSION['uniacid'],'mid'=>$data['setmid']));
		$passtime = TIMESTAMP-$chat['lasttime'];
		$kefuremindtime = $setting['kefuremindtime'] ? $setting['kefuremindtime'] :120;
		if($passtime > $kefuremindtime){
			if($type == 4){
					$tplcon = $data['nickname'].'发送了图片';
			}elseif($type == 3){
						$tplcon = $data['nickname'].'发送了语音';
			}elseif($type == 7){
						$tplcon = $data['nickname'].'发送文件';
			}else{
				if(strpos($data['msg'],'span class=')){
								$tplcon = $data['nickname'].'发送了表情';
				}else{
								$tplcon = $data['msg'];
				}
			}
			$tplcon=strip_tags(str_replace('&nbsp;','',$tplcon));
			$tplcon = cfc('tools')->filterword($tplcon,$setting['filterword']);
			$kefumid = pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'openid'=>$_SESSION['openid']),array('mid'));
			if(!empty($setting['tpl_kefu']) && $setting['isremind'] && false){
				//目前消息提醒的已经没有了！
				//$template_id=cfc('account')->get_tpl_template_id('50766','订单取消通知','',array('订单金额','商品名称','配送地址','订单号'),'cancel2buyer','jy_weishop');
				$url = custom_url('jy_kefu/chat//getmid='.$data['setmid'],true);
				$topcolor = '#980000';
				$msg = array(
									'first' => array(
										'value' => $data['nickname'].'向您发了信息！',
										'color' => '#990000'
									),
									'keyword1' => array(
										'value' => $tplcon,
										'color' => '#ff510'
									),
									'keyword2' => array(
										'value' => "点击此消息尽快回复",
										'color' => '#ff510'
									),
									'remark' => array(
										'value' => '咨询时间：'.date("Y-m-d H:i:s",TIMESTAMP),
										'color' => '#ff510'
									),							
				);
				$res = cfc('account')->sendTplNotice($getmid,$setting['tpl_kefu'],$msg,$url,$topcolor);
			}else{
				$url = custom_url('jy_kefu/chat//getmid='.$data['setmid'],true);
				$concon = $data['nickname'].'向你发了信息！内容:'.$tplcon.'。';
				$msg = array();
				$msg['title'] = '新消息提醒';
				$msg['description'] = $concon;
				$msg['url'] = $url;
				$msg['picurl'] = tomedia($_SESSION['member']['avatar']);
				$news[] = $msg;
				$senddata['msgtype'] = 'news';
				$senddata['news']['articles'] = $news;
				$res = cfc('account')->sendCustomNotice($senddata,$getmid);
			}
		}
		$update=array('meisdel'=>0,'getisdel'=>0,'lastmsg'=>$chatmsg,'msgtype'=>$type,'lasttime'=>TIMESTAMP);
		pdo_update('jy_kefu_member_chat',$update,array('chatid'=>$data['chatid'],'mid'=>$data['setmid'],'uniacid'=>$_SESSION['uniacid']));
		$return['error'] = 0;
		$audiotime = $data['type'] == 3 ? $data['audiotime'].'\'\' ' : '';
		$audioleng = $data['audiotime'] >2 ? $data['audiotime']:'2';
		$datetime = date("Y-m-d H:i:s",$data['time']);
		$getmemberlogo=$this->session('getmemberlogo');
		$memberlogo=$this->session('memberlogo');
		if($_SESSION['os']=='windows'){
						if($type == 1){
								$html .='<div class="message_box from_self"><img class="mssage_box_pic" src="'.$memberlogo.'" style="display:inline-block;"/><div class="message_content"><div class="message_content_inner"><p>'.$chatmsg.'</p></div></div></div>';
						}elseif($type == 3){
							$chatmsg=tomedia($chatmsg);
							if($v['setmid'] != $_SESSION['uid']){
									$playhtml = '<span ng-show="pagedata.playon == 1" ng-click="pagedata.playon =0" style="display:none;width:'.$v['audioleng'].'rem;text-align:right" class="text kefu-playon"><img src="../core/resource/images/audioplaying.gif"/></span><span ng-show="pagedata.playon !=1" ng-click="pagedata.playon =1" style="width:'.$v['audioleng'].'rem;text-align:right" class="text icon jinyunicon icon-shengbo"></span>';
									$html .='<div onclick="playaudio(\''.$chatmsg.'\');" class="r clearfix"><img class="pic"/><span>'.$v['audiotime'].'\'\'</span>'.$playhtml.'</div>';
							}else{
									if($v['isread'] != 1){
										$unread = '<span class="unread"></span>';
									}else{
										$unread ='';
									}
									$playhtml = '<span ng-show="pagedata.playon !=1" ng-click="pagedata.playon =1" style="width:'.$v['audioleng'].'rem" class="text icon jinyunicon icon-shengbo"></span>';
									$html .='<div onclick="playaudio(\''.$chatmsg.'\',\'\','.$v['id'].');" class="l clearfix"><img class="pic"/>'.$playhtml.'<span>'.$v['audiotime'].'\'\'</span>'.$unread.'</div>';
							}
							$html .= $htmltime;
						}elseif($type == 4){
							$chatmsg=tomedia($chatmsg);
								$html .='<div class="message_box from_self"><img class="mssage_box_pic" src="'.$memberlogo.'" style="display:inline-block;"/><div class="message_content"><p onclick="followewm(\''.$chatmsg.'\');" class="message_content_inner media"><img src="'.$chatmsg.'" style="width:100%;"/></p></div></div>';
						}elseif($type == 7){
							$fileurl=tomedia($chatmsg);
							$pathinfo=pathinfo($chatmsg);
							$fileicon=$pathinfo[extension];
							$filename=pdo_getcolumn('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'attachment'=>$chatmsg),'title');
							$filename=$filename.'.'.$pathinfo[extension];
							if(strpos($fileicon,'xls')){
								$fileicon='icon-exl';
							}elseif(strpos($fileicon,'pd')){
								$fileicon='icon-pdf';
							}elseif(strpos($fileicon,'do')){
								$fileicon='icon-exl';
							}elseif(strpos($fileicon,'zip') || strpos($fileicon,'rar')){
								$fileicon='icon-zip';
							}else{
								$fileicon='icon-copy';
							}
							$filesize=filesize(ROOT_AT.'/'.$chatmsg)/1000;
							$filesize=$filesize.'kb';
							$html .='<div class="message_box from_self"><img class="mssage_box_pic" src="'.$memberlogo.'" style="display:inline-block;"/><div class="message_content"><div class="message_content_inner"><a href="'.$fileurl.'" target="_blank" class="fui-cell"><div class="text"><div>'.$filename.'</div><div style="font-size:12px">'.$filesize.'</div></div><div class="icon"><i class="icon '.$fileicon.'"></i></div></a></div></div></div>';
						}
		}else{
			if($type == 1){
				$html .='<div class="r clearfix"><img class="pic"/><p class="text">'.$chatmsg.'</p></div>';
			}elseif($type == 3){
				$playhtml = '<span ng-click="pagedata.playon ='.$logid.'" style="width:'.$audioleng.'rem;text-align:right" class="text icon jinyunicon icon-shengbo"></span>';
				$html .='<div onclick="playaudio(\''.$chatmsg.'\');" class="r clearfix"><img class="pic"/><span>'.$audiotime.'</span>'.$playhtml.'</div>';
			}elseif($type == 4){
				$chatmsg = tomedia($chatmsg);
				$html .='<div class="r clearfix"><img class="pic"/><p onclick="followewm(\''.$chatmsg.'\');"  class="textimg"><img style="max-width:100%" src="'.$chatmsg.'"/></p></div>';
			}elseif($type == 7){
				$fileurl=tomedia($chatmsg);
				$pathinfo=pathinfo($chatmsg);
				$fileicon=$pathinfo[extension];
				$filename=pdo_getcolumn('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'attachment'=>$chatmsg),'title');
				$filename=$filename.'.'.$pathinfo[extension];
				if(strpos($fileicon,'xls')){
					$fileicon='icon-exl';
				}elseif(strpos($fileicon,'pd')){
					$fileicon='icon-pdf';
				}elseif(strpos($fileicon,'do')){
					$fileicon='icon-exl';
				}elseif(strpos($fileicon,'zip') || strpos($fileicon,'rar')){
					$fileicon='icon-zip';
				}else{
					$fileicon='icon-copy';
				}
				$filesize=filesize(ROOT_AT.'/'.$chatmsg).'kb';
				$html .='<div class="r clearfix"><img class="pic"/><div class="text"><a href="'.$fileurl.'" target="_blank" class="fui-cell"><div class="text"><div>'.$filename.'</div><div style="font-size:12px">'.$filesize.'</div></div><div class="icon"><i class="icon '.$fileicon.'"></i></div></a></div></div>';
			}
		}
		$return['htmlmsg']=$html;
		$return['audiotime']=$audiotime;
		$return['audioleng']=$audioleng;
		$return['id']=$logid;
		return $return;
	}
}